import { createSlice } from "@reduxjs/toolkit";
import { Login } from "@/api/user";
import { setToken, getToken, removeToken } from "@/utils";
import storage from "@/utils/cache";


const userInfoStore = createSlice({
  name: "userInfo",
  initialState: {
    userInfo: {},
    token: getToken() || "",
  },
  reducers: {
    SET_TOKEN(state, action) {
      state.token = action.payload;
      setToken(action.payload);
    },
    SET_USERINFO(state, action) {
      state.userInfo = action.payload;
    },
    LOGIN_OUT(state) {
      state.token = ""
      state.userInfo = {}
      removeToken()
      storage.session.clear()
      storage.local.clear()
    }

  },
});
const { SET_TOKEN, SET_USERINFO, LOGIN_OUT } = userInfoStore.actions;

// 登录
const login = (data) => {
  return async (dispatch) => {
    const result = await Login({ ...data });
    dispatch(SET_TOKEN(result.token));
  };
};

// 退出登录
const loginOut = () => {
  return async (dispatch) => {
    dispatch(LOGIN_OUT());
  };
};

const reducer = userInfoStore.reducer;

export { login, loginOut };
export default reducer;
